package com.quanyan.ic.vendingMachine.remoting.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.ic.common.http.APIResponse;
import com.quanyan.ic.common.http.exception.BizException;
import com.quanyan.ic.vendingMachine.model.OrderPreparedResult;
import com.quanyan.ic.vendingMachine.model.ShoppingCartItem;
import com.quanyan.ic.vendingMachine.remoting.OrderRemotingService;
import com.quanyan.ic.vendingMachine.remoting.request.PlaceGoodsInfo;
import com.quanyan.ic.vendingMachine.remoting.request.ReqPlaceOrder;
import com.quanyan.ic.vendingMachine.remoting.response.RespPlaceOrderInfo;
import com.quanyan.ic.vendingMachine.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jian.zhou on 2017/8/2.
 */
@Service
public class OrderRemotingServiceImpl implements OrderRemotingService {

    private static final Logger logger = LoggerFactory.getLogger(OrderRemotingServiceImpl.class);

    @Value("${place.server.url}")
    private String placeServiceUrl; //场馆服务地址
    private final static String returnOrderNoAndCodeData = "/admin/api/place/goods/returnOrderNoAndCodeData";   //返回扫描二维码预下单接口

    /**
     * 调用 http 服务，在场馆服务端做小商品预下单
     */
    private RespPlaceOrderInfo queryOrderNoAndCodeData(ReqPlaceOrder reqPlaceOrder) {
        String url = placeServiceUrl + returnOrderNoAndCodeData;
        String params = JSONObject.toJSONString(reqPlaceOrder);
        logger.info("call remote place order service:\nurl={}\nparams={}", url, params);
        String respStr = null;
        APIResponse response = null;
        try {
            respStr = HttpClientUtils.postJson(url, params);
            response = JSONObject.parseObject(respStr, APIResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(respStr) || response == null) {
            logger.error("call remote place order service error: resp=null");
            return null;
        }
        if (!response.isRet() || response.getData() == null) {
            logger.error("call remote place order service error: {}", response.getErrmsg());
            throw new BizException("下单失败，请重试！");
        }
        RespPlaceOrderInfo respPlaceOrderInfo = JSONObject.parseObject(response.getData().toString(), RespPlaceOrderInfo.class);
        logger.info("call remote place order service result: {}", JSON.toJSONString(respPlaceOrderInfo));
        return respPlaceOrderInfo;
    }

    /**
     * 售货机商品预下单
     *
     * @param placeId              场馆id
     * @param vmNumber             售货机编号
     * @param shoppingCartItemList 购物清单
     * @return
     */
    @Override
    public OrderPreparedResult preOrder(Integer placeId, String vmNumber, List<ShoppingCartItem> shoppingCartItemList, HttpServletRequest request) {
        if (placeId == null || StringUtils.isEmpty(vmNumber)
                || shoppingCartItemList == null || shoppingCartItemList.size() == 0) {
            return null;
        }
        ReqPlaceOrder req = new ReqPlaceOrder();
        req.setPlaceId(placeId);
        req.setSaleMachineNo(vmNumber);
        List<PlaceGoodsInfo> placeGoodsInfoList = new ArrayList<>();
        for (ShoppingCartItem item : shoppingCartItemList) {
            PlaceGoodsInfo goodsInfo = new PlaceGoodsInfo();
            goodsInfo.setId(item.getId());
            goodsInfo.setGoodsId(item.getUuid());
            goodsInfo.setGoodsCount(item.getQty());
            placeGoodsInfoList.add(goodsInfo);
        }
        req.setGoodsList(placeGoodsInfoList);
        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        req.setUrl(serverUrl + "/larkic/vendingMachine/order/scanQrCodePay/callback"); //
        RespPlaceOrderInfo resp = this.queryOrderNoAndCodeData(req);
        if (resp == null) {
            return null;
        }
        OrderPreparedResult result = new OrderPreparedResult();
        if (StringUtils.isEmpty(resp.getWeixinCodeUrl()) && StringUtils.isEmpty(resp.getPayCodeUrl())) {
            logger.error("prepared order codeUrl is null, return error: a={} w={}", resp.getPayErrMsg(), resp.getWeixinErrMsg());
            return null;
        }
        result.setOrderNo(resp.getOrderNo());
        result.setAliPayCode(resp.getPayCodeUrl());
        result.setWchatPayCode(resp.getWeixinCodeUrl());
        return result;
    }
}
